library Wave6 initializer init requires LegacySystem

    private function SentryCoordinates_Actions takes nothing returns nothing
        local integer A = 1
        loop
            exitwhen A > udg_nSurveillanceArea        
        if udg_SurveillanceIncomplete[A] then
                call TriggerSleepAction(0.05)
                call PingMinimapEx(GetLocationX(udg_SAlocs[A]), GetLocationY(udg_SAlocs[A]), 20.0, 255, 0, 0, false)
        endif
            set A = A + 1
        endloop
    endfunction
    
    private function SentryCoordinatesLoop takes nothing returns nothing
        call SentryCoordinates_Actions()
        if udg_SurveillanceComplete==5 or udg_CurrentWave!=6 then
            call DestroyTrigger(GetTriggeringTrigger())
        endif
    endfunction

    private function GroupSelectGround takes nothing returns boolean
        return IsUnitType(GetFilterUnit(), UNIT_TYPE_FLYING)!=true
    endfunction


    private function wave6_GenLocs takes nothing returns nothing
        local integer A = 1
        local integer B
        local integer n = udg_nSurveillanceArea
        local location tryloc
        loop
            exitwhen A > n
            set tryloc = GetRandomLocInRect(bj_mapInitialPlayableArea)
            set B = 1
            loop
                if B>=A then //No locations overlapped
                    set udg_SAlocs[A] = tryloc
                    set A = A + 1
                    exitwhen true
                endif
                if DistanceBetweenPoints(tryloc,udg_SAlocs[B])<2*udg_SurvRadius then
                    exitwhen true  //Try a new location
                endif
                set B = B + 1
            endloop
        endloop
    endfunction

    private function CircleContainsUnit takes unit u, location l, real r returns boolean
        local real dx = GetLocationX(l) - GetUnitX(u)
        local real dy = GetLocationY(l) - GetUnitY(u)
        return SquareRoot(dx * dx + dy * dy)<r
    endfunction

    private function UnitInSentryRegion takes unit u returns integer
        local integer A = 1
        loop
            exitwhen A>udg_nSurveillanceArea
                if udg_CurrentWave==6 and udg_SurveillanceIncomplete[A] and CircleContainsUnit(u,udg_SAlocs[A],udg_SurvRadius) then
                    return A
                endif
            set A=A+1
        endloop
        return -1
    endfunction

  


    private function SentryPlacementConditions takes nothing returns boolean
        return GetSpellAbilityId()=='A07T'
    endfunction

    private function SentryPlacement takes nothing returns nothing
        local unit u = GetTriggerUnit()
        local unit u2
        local real x = GetUnitX(u)
        local real y = GetUnitY(u)
        local item sentry
        local player p = GetOwningPlayer(u)
        local integer i = 1
        set udg_myint = UnitInSentryRegion(u)
        if udg_Mode==3 then
            set udg_myint=udg_SurveillanceComplete
        endif
        if udg_myint==-1 then
            call IssueImmediateOrder(u,"holdposition")
            call DisplayTimedTextToPlayer(p,0.0,0.0,2.0, "Sentries must be set up in designated areas." )
        elseif udg_CurrentWave!=6 or udg_SurveillanceComplete>5 then
            call IssueImmediateOrder(u,"holdposition")
        elseif udg_CurrentWave==6 or udg_Mode==3 then
            set u2 = CreateUnit(p,'hwtw',x,y,0.0)
            call SetUnitColor(u2,PLAYER_COLOR_RED)
            set udg_SurveillanceIncomplete[udg_myint] = false
            set sentry = GetUnitItem(u,'I017')
            call UnitRemoveItem(u,sentry)
            call RemoveItem(sentry)
            set bj_meleeNearestMineDist = GetUnitX(u)
            set bj_lastTransmissionDuration = GetUnitY(u)
            set udg_soundpath = "Units\\Orc\\StasisTotem\\StasisTrapBirth.wav"
            call PlaySoundPath3D.execute()
            call DisplayTimedTextToPlayer(p,0.0,0.0,2.0,"Connecting to GPS Network..")
            call PolledWait(2.)
            set bj_meleeNearestMineDist = GetUnitX(u2)
            set bj_lastTransmissionDuration = GetUnitY(u2)
            set udg_soundpath = "Abilities\\Spells\\Undead\\DevourMagic\\DevourMagic.wav"
            call PlaySoundPath3D.execute()
            call PolledWait(2.)
            set bj_meleeNearestMineDist = GetUnitX(u2)
            set bj_lastTransmissionDuration = GetUnitY(u2)
            set udg_soundpath = "Abilities\\Spells\\Items\\Alre\\RestorationPotion.wav"
            call PlaySoundPath3D.execute()
            call SetUnitColor(u2,PLAYER_COLOR_BLUE)
            set udg_SurveillanceComplete=udg_SurveillanceComplete+1
            call ALICEText(3.0, "Sentry activated at coordinates ( " + I2S(R2I(x)) + ", " + I2S(R2I(y)) + " )." )
            call PingMinimapEx(x,y,12.0,0,200,0,false)
            call MultiboardSetTitleText( udg_SquadStatus, "Active Sentries - " + I2S(udg_SurveillanceComplete) )
            if udg_SurveillanceComplete<=5 and udg_Mode==1 then
                call ALICEText(3.0, "Surveillance Sentry Online. |cff1e90ff15 XP|r awarded to all Marines." )
                loop
                    exitwhen i>udg_InitialPlayers
                    if GetPlayerSlotState(ConvertedPlayer(udg_Sorted[i]))!=PLAYER_SLOT_STATE_LEFT then
                        set udg_Experience[udg_Sorted[i]] = udg_Experience[udg_Sorted[i]] + 15
                    endif
                    set i=i+1
                endloop
            endif
            set u2=null
        endif
        set u=null
        set sentry=null
    endfunction

    private function Wave6a takes nothing returns nothing
        local real timerfactor = 0
        local group g = GetUnitsOfPlayerMatching(Player(9), Condition(function GroupSelectGround))
        local timerdialog d
        local integer i
        local integer sentrymission = 0
        local trigger t
        local timer mission = CreateTimer()
        call wave6_GenLocs()
        call SetPlayerName(Player(9),"Civilians")
        call ForGroup(g,function RemoveUnitAll)
        call DestroyGroup(g)
        set g = null
        set udg_AITarget = null
        if GetWidgetLife(udg_CommArray)<=0.405 then
            call SetForceAllianceStateBJ(bj_FORCE_PLAYER[9],udg_EchoCompany,bj_ALLIANCE_ALLIED)
            call SetForceAllianceStateBJ(bj_FORCE_PLAYER[11],udg_EchoCompany,bj_ALLIANCE_ALLIED)
        endif
        call FieldChat(udg_Ogilvy, 5.0, "|cfff3ad00Ogilvy|r : We're safe now. You did a good thing today Marines." )

        if udg_ConvoyClear>1 then
            set i = GetRandomInt(1,udg_Players)
            call FieldChat(udg_Hero[udg_Sorted[i]], 5.0, udg_Pcolors[udg_Sorted[i]] + GetPlayerName(ConvertedPlayer(udg_Sorted[i])) + "|r : Convoy is secure." )
        endif


        // ============================================
        // DEBUG MESSEGE 
        // =============================================
        call debugmsg("dropping wave 6 items in 3 seconds")
        // =============================================

        call PolledWait(3.)
        call FieldChat(udg_DeltaLeader, 5.0, "|cfff3ad001Lt. Rasczak|r : We're heading back. I wish we could spare you some men, but we're under strict orders not to compromise convoy security. God speed." )
        call PolledWait(10.0*udg_Pace)
        call ForGroup(udg_InfantryGroup[1],function RemoveUnitAll)
        set udg_CurrentWave = 6
        set udg_Visibility = 69
        call IntermissionRestore()
        set udg_Visibility = 68
        call IntermissionRestore()
        call GenericActions.execute()
        call DisplayTextToPlayer( GetLocalPlayer(),0.0,0.0, "|cffcd950cBattalion|r : C-130s have airdropped additional equipment to your region. Organize fire teams for retrieval and resupply." )
        if udg_Players<4 then
            call RandomSpawn('uabo',1,1) //Flesh Composite
            call RandomSpawn('nsw1',1,1+udg_Spawn) //Stalker
        else
            call RandomSpawn('uabo',1,2) //Flesh Composite
            call RandomSpawn('nsw1',1,3+udg_Spawn) //Stalker
        endif
        call MBSet(udg_SquadStatus,1,1, "Objective : Reconnaissance" )
        call QuestSetDescription(udg_CurrentOrders, "Additional supplies have landed in your sector. Retrieve them. Marines should move in pairs to provide covering fire." )
        call MissionUpdate.execute()

        
        call C130Wave6.execute()
        
        set sentrymission=1
        
        call PolledWait(15.0*udg_Pace)
        set i = GetRandomInt(1,udg_Players)
        call FieldChat(udg_Hero[udg_Sorted[i]],5.0, udg_Pcolors[udg_Sorted[i]] + GetPlayerName(ConvertedPlayer(udg_Sorted[i])) + "|r : That almost turned into a charlie foxtrot." )
        call PolledWait(15.0*udg_Pace)
        call SatelliteCamera.execute()
        call PolledWait(15.0*udg_Pace)
        if sentrymission==1 then
            call GeneralText(8.0, "|cffcd950cBattalion|r : We have to establish a Surveillance Network in the sector to monitor activity." )
            call PolledWait(12.0*udg_Pace)
            call GeneralText(5.0, "|cffcd950cBattalion|r : Set up five surveillance sentries at the following locations." )
        endif
       // call DestroyTrigger(gg_trg_Convoy_Exit)
        if sentrymission==1 then
            call SentryCoordinates_Actions()
            set t = CreateTrigger()
            call TriggerRegisterTimerEvent(t,35.0,true)
            call TriggerAddAction(t,function SentryCoordinatesLoop)
            set t = null
        endif
        call PolledWait(5.)
        if sentrymission==1 then
            call MBSet( udg_SquadStatus, 1, 1, "Objective : Set Up Surveillance Network" )
            call QuestSetDescription(udg_CurrentOrders, "Live updates of Sector E required by CP. Place 5 surveillance sentries at designated areas before the window of opportunity is closed. There are 4 Surveillance Sentries in the Power Generator (South East) and 2 at the Windmill (North West). |n|nPlant the sentries inside the marked regions. Surveillance Sentries also contain three EM charges for use with a Transceiver." )
            call ALICEText(5.0, "|cff8b864eNew Objective|r : Set Up Surveillance Network." )
            call MissionUpdate.execute()
        endif
        call PolledWait(5.)
        call SetDynamicEvasionEnabled(false)
        call SetSmartGrenadesEnabled(false)
        
        set i = GetRandomInt(1, udg_Players)
        call FieldChat(udg_Hero[udg_Sorted[i]],8.0, udg_Pcolors[udg_Sorted[i]] + GetPlayerName(ConvertedPlayer(udg_Sorted[i])) + "|r : You heard the Skipper. Let's move out!" )
        if sentrymission==1 then
            call MultiboardSetTitleText( udg_SquadStatus, "Active Sentries : " + I2S(R2I(udg_SurveillanceComplete)) )
        endif
        call RandomSpawn('n00N',1,GetRandomInt(0,3)) //Mass HP Zombie
        if GetRandomInt(0,40)==1 and udg_SquadXP>25000 then
            call RandomSpawn('n00X',2,1) //Evil Dog
        endif
        call SpawnRectRandom(gg_rct_SpawnEastCave,Player(13),'nzom',4+udg_Spawn)
        call SpawnRectRandom(gg_rct_SpawnTownWestCave,Player(13),'n00M',udg_Spawn)
        if GetRandomInt(1,5)==1 then
            call SpawnRectRandom(gg_rct_SpawnSouthWaterfall,Player(14),'n00C',udg_Spawn)
            call SpawnRectRandom(gg_rct_SpawnWestCave,Player(14),'n00C',udg_Spawn)
        else
            call SpawnRectRandom(gg_rct_SpawnSouthWaterfall,Player(14),'u000',2+udg_Spawn)
            call SpawnRectRandom(gg_rct_SpawnWestCave,Player(14),'u000',2+udg_Spawn)
            call SpawnRectRandom(gg_rct_SpawnNorthWaterfall,Player(14),'u000',2+udg_Spawn)
        endif
        call SetPopperExplosionControlEnabled(true)
        if udg_SquadXP>55000 then
            call GankMarine(Player(13),'u00U',udg_Spawn,3500,4500) //Popper sequence
        endif
        call PolledWait(5.)
        if udg_SquadXP>50000 then
            set timerfactor = I2R(udg_Players)*25.0
        else
            set timerfactor = I2R(udg_Players)*20.0
        endif
        if sentrymission==1 then
            call ALICEText(5.0, "|cffcd950cALICE|r : Retrieve Sentries at the Power Generator and Windmill." )
            call TimerStart(mission,380.0-timerfactor,false,null)
            set d = CreateTimerDialog(mission)
            call TimerDialogSetTitle(d,"Channels Open")
            call TimerDialogDisplay(d, true)
        endif
        set udg_soundpath = "Units\\Undead\\Banshee\\BansheeDeath.wav"
        call PlaySoundPath.execute()
        call PolledWait(20.)

        call SpawnShredder()

        if udg_SquadXP>30000 then
            call RandomSpawn('e00Q',2,udg_Spawn) // Parasite Mound
        else
            call SpawnRectRandom(gg_rct_SpawnNorthWaterfall,Player(13),'n00M',udg_Spawn)
        endif
        call SpawnRectRandom(gg_rct_SpawnWestCave,Player(13),'nzom',4+udg_Spawn)
        if sentrymission==1 then
            call GeneralText(6.0, "|cfff3ad00Marine|r : We don't have much time. We'll cover more ground if we split up. There's no telling what's out there. Move in pairs." )
        else
            call GeneralText(6.0, "|cfff3ad00Marine|r : We've got a few more minutes of recon time. Gather as many supplies as we can and consolidate." )
        endif
        call LightningAmbience.execute()
        if GetRandomInt(1,7)==1 then
            if GetRandomInt(0,1)==1 then
                set udg_soundpath = "Sound\\Dialogue\\HumanCampaign\\Human01\\H01VillagerC37.mp3"
                call PlaySoundPath.execute()
            else
                set udg_soundpath = "Sound\\Dialogue\\HumanCampaign\\Human01\\H01VillagerC36.mp3"
                call PlaySoundPath.execute()
            endif
        endif
        call PolledWait(300.0-timerfactor)
        if sentrymission==1 then
            call TimerDialogSetTimeColor(d,242,0,0,255)
        endif
        if udg_SquadXP>50000 and GetRandomInt(0,20)==1 then
            call RandomSpawn('u003',8,udg_Spawn) //Ghoul #3
        else
            call RandomSpawn('u003',4,udg_Spawn) //Ghoul #3
        endif
        call PolledWait(60.)
        call GeneralText(5.0, "|cfff3ad00Marine|r : Haul ass and regroup. Recon sats are picking up more incoming." )
        set i = 1
        loop
            exitwhen i>udg_Players
            call UnitRemoveAbility( udg_Hero[GetConvertedPlayerId(ConvertedPlayer(udg_Sorted[i]))], 'AIbt' )
            set i=i+1
        endloop
        call SetPopperExplosionControlEnabled(false)
        if sentrymission==1 then
            call TimerDialogDisplay(d,false)
            call DestroyTimerDialog(d)
            call PauseTimer(mission)
            call DestroyTimer(mission)
            set d = null
        endif
        if udg_Players>0 then
            if udg_SquadXP>3500 and ((udg_Difficulty>4.0 and GetRandomInt(0,1)==1) or (udg_Difficulty<4.0 and GetRandomInt(0,2)==1)) and udg_Mode!=2 then
                call ExecuteRegisteredFunction("Wave7c")
                //call Wave7c.execute()
            else
                call ExecuteRegisteredFunction("Wave7a")
                //call Wave7a.execute()
            endif
        endif
    endfunction

    private function init takes nothing returns nothing
        local trigger t 
        set t = CreateTrigger()
        call TriggerRegisterAnyUnitEventBJ(t, EVENT_PLAYER_UNIT_SPELL_EFFECT)
        call TriggerAddCondition( t, Condition( function SentryPlacementConditions ))
        call TriggerAddAction(t,function SentryPlacement)
        
         call RegisterFunction("Wave6a", function Wave6a)
    endfunction
    
endlibrary